<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Form, Field } from "vee-validate";
import { ElMessage } from "element-plus";
import type { LoginParams } from "@/types/userTypes/userTypes.ts";
import type { Router, RouteLocationNormalized } from "vue-router";
import validates from "@/utils/validates.ts";
import useUserStore from "@/pinia/modules/userStore/userStore.ts";
import useShopCartStore from "@/pinia/modules/shopCartStore/shopCartStore.ts";
import Checkbox from "@/components/lib/Checkbox.vue";

const userStore = useUserStore();

const shopCartStore = useShopCartStore();

const router: Router = useRouter();

const route: RouteLocationNormalized = useRoute();

const isMsgLogin = ref<boolean>(false);

const formRef = ref();

const loading = ref<boolean>(false);

let time: any = null;

let timeOut = ref<number>(10);

const formData = reactive<LoginParams>({
   account: "xiaotuxian001",
   password: "123456",
   mobile: "13666666666",
   code: "",
   isAgree: true,
});

const formRules = {
   ...validates,
};


const text = computed<string>(() => loading.value ? "登录中" : "登录");


/*发送验证码按钮的回调函数*/
const sendCode = async () => {
   try {
      const validate = formRules.mobile(formData.mobile as string);
      if (typeof validate !== "boolean") return;
      if (timeOut.value < 10) return;
      clearInterval(time);
      time = setInterval(() => {
         timeOut.value--;
         if (timeOut.value <= 0) {
            clearInterval(time);
            timeOut.value = 10;
         }
      }, 1000);
      const code: string = await userStore.sendCode(formData!.mobile as string);
      formData.code = code;
      ElMessage.success("验证码发送成功");
   } catch (error: any) {
      ElMessage.error(error.message);
   }
};


/*登录按钮的回调函数*/
const handleLogin = async () => {
   const validate = await formRef.value.validate();
   if (!validate) return ElMessage.error("请完善登录信息");
   if (isMsgLogin.value) {
      try {
         loading.value = true;
         const loginResult: string = await userStore.userMobileLogin({ mobile: formData.mobile, code: formData.code } as LoginParams);
         await shopCartStore.mergeCart();
         ElMessage.success(loginResult);
         router.push((route.query.redirectUrl as string) || "/");
      } catch (error: any) {
         ElMessage.error(error.message);
      } finally {
         loading.value = false;
      }
   } else {
      try {
         loading.value = true;
         const loginResult: string = await userStore.userNameLogin({ account: formData.account, password: formData.password } as LoginParams);
         await shopCartStore.mergeCart();
         ElMessage.success(loginResult);
         router.push((route.query.redirectUrl as string) || "/");
      } catch (error: any) {
         ElMessage.error(error.message);
      } finally {
         loading.value = false;
      }
   }
};


onMounted(() => {
   /*
   QC.Login({
         btnId: "qqLoginBtn",
    });
   */
});

</script>


<template>
   <div class="account-box">
      <!--切换登录方式-->
      <div class="toggle">
         <a @click="isMsgLogin=false" v-if="isMsgLogin">
            <i class="iconfont icon-user"></i>
            <a>使用账号登录</a>
         </a>
         <a @click="isMsgLogin=true" v-else>
            <i class="iconfont icon-msg"></i>
            <a>使用短信登录</a>
         </a>
      </div>
      <Form class="form" ref="formRef" :validation-schema="formRules" v-slot="{errors}">
         <!--账号登录-->
         <template v-if="!isMsgLogin">
            <div class="form-item">
               <div class="input">
                  <i class="iconfont icon-user"></i>
                  <Field :class="{error:errors.account}" type="text" placeholder="请输入用户名或手机号" name="account" v-model="formData.account" />
               </div>
               <div class="error" v-if="errors.account"><i class="iconfont icon-warning" />{{ errors.account }}</div>
            </div>
            <div class="form-item">
               <div class="input">
                  <i class="iconfont icon-lock"></i>
                  <Field :class="{error:errors.password}" type="password" placeholder="请输入密码" name="password" v-model="formData.password" />
               </div>
               <div class="error" v-if="errors.password"><i class="iconfont icon-warning" />{{ errors.password }}</div>
            </div>
         </template>
         <!--手机号登录-->
         <template v-else>
            <div class="form-item">
               <div class="input">
                  <i class="iconfont icon-user"></i>
                  <Field :class="{error:errors.mobile}" type="text" placeholder="请输入手机号" name="mobile" v-model="formData.mobile" />
               </div>
               <div class="error" v-if="errors.mobile"><i class="iconfont icon-warning" />{{ errors.mobile }}</div>
            </div>
            <div class="form-item">
               <div class="input">
                  <i class="iconfont icon-code"></i>
                  <Field :class="{error:errors.code}" type="text" placeholder="请输入验证码" name="code" v-model="formData.code" />
                  <span class="code" @click="sendCode">{{ timeOut === 10 ? `发送验证码` : `${timeOut}S` }}</span>
               </div>
               <div class="error" v-if="errors.code"><i class="iconfont icon-warning" />{{ errors.code }}</div>
            </div>
         </template>
         <div class="form-item">
            <div class="agree">
               <Field :as="Checkbox" name="isAgree" v-model="formData.isAgree" />
               <span>我已同意</span>
               <a>《隐私条款》</a>
               <span>和</span>
               <a>《服务条款》</a>
            </div>
            <div class="error" v-if="errors.isAgree"><i class="iconfont icon-warning" />{{ errors.isAgree }}</div>
         </div>
         <button class="btn" :disabled="loading" @click="handleLogin">{{ text }}</button>
      </Form>
      <div class="action">
         <!--<span id="qqLoginBtn"></span>-->
         <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
            <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
         </a>
         <div class="url">
            <a>忘记密码</a>
            <a>免费注册</a>
         </div>
      </div>
   </div>
</template>

<style scoped lang="less">
.account-box {
   .toggle {
      padding: 20px 40px;
      text-align: right;

      a {
         color: @xtxColor;

         i {
            font-size: 14px;
         }
      }
   }

   .form {
      padding: 0 40px;

      &-item {
         margin-bottom: 28px;

         .input {
            position: relative;
            height: 36px;

            > i {
               width: 34px;
               height: 34px;
               background: #cfcdcd;
               color: #fff;
               position: absolute;
               left: 1px;
               top: 1px;
               text-align: center;
               line-height: 34px;
               font-size: 18px;
            }

            input {
               padding-left: 44px;
               border: 1px solid #cfcdcd;
               height: 36px;
               line-height: 36px;
               width: 100%;

               &.error {
                  border-color: @priceColor;
               }

               &.active, &:focus {
                  border-color: @xtxColor;
               }
            }

            .code {
               position: absolute;
               right: 1px;
               top: 1px;
               text-align: center;
               line-height: 34px;
               font-size: 14px;
               background: #f5f5f5;
               color: #666;
               width: 90px;
               height: 34px;
               cursor: pointer;
            }
         }

         > .error {
            position: absolute;
            font-size: 12px;
            line-height: 28px;
            color: @priceColor;

            i {
               font-size: 14px;
               margin-right: 2px;
            }
         }
      }

      .agree {
         a {
            color: #069;
         }
      }

      .btn {
         display: block;
         width: 100%;
         height: 40px;
         color: #fff;
         text-align: center;
         line-height: 40px;
         background: @xtxColor;
         border: 0;
         cursor: pointer;

         &:hover {
            background: #18bd76;
         }

      }
   }

   .action {
      padding: 20px 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .url {
         a {
            color: #999;
            margin-left: 10px;
         }
      }
   }
}
</style>
